package com.example.onlinemonitoring.serviceImpl;

import com.example.onlinemonitoring.Util.ConditionDispose;
import com.example.onlinemonitoring.Util.DefaultProperty;
import com.example.onlinemonitoring.dao.DtshistoryMapper;
import com.example.onlinemonitoring.dao.DtspartitionMapper;
import com.example.onlinemonitoring.dao.DtsphistoryMapper;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Dtspartition;
import com.example.onlinemonitoring.model.Dtsphistory;
import com.example.onlinemonitoring.model.Dtssensor;
import com.example.onlinemonitoring.model.Dtshistory;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.common.alarmmessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.onlinemonitoring.Util.tem.SensorAbstractBaseService;
import com.example.onlinemonitoring.service.DtssensorService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.example.onlinemonitoring.model.common.chartres;
import com.example.onlinemonitoring.model.common.pagebase;
import com.example.onlinemonitoring.Util.HexUtil;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description Dtssensor接口实现
* @author  generator
* @since  2022-04-09 13:03:09
*/
@Service("dtsServiceImpl")
public class DtssensorServiceImpl extends SensorAbstractBaseService<Dtssensor, Dtshistory> implements DtssensorService {
    
    @Autowired
    private DtspartitionMapper dtspartitionMapper;
    @Autowired
    private DtsphistoryMapper dtsphistorymapper;
    @Autowired
    private DtshistoryMapper dtshistorymapper;

    public int Add(Appdevice record) {
        int ret = 1;
        Example example = new Example(Dtssensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid",record.getStationid());
        criteria.andEqualTo("devicegroup",record.getDevicegroup());
        criteria.andEqualTo("ipaddr",record.getIp());
        for (int i = record.getAddrmin(); i < record.getAddrmax() + 1; i++) {
            Dtssensor sensor = new Dtssensor();
            sensor.setIpname(record.getIp());
            sensor.setPointname("通道"+i);
            sensor.setIpaddr(record.getIp());
            sensor.setChunk(i);
            criteria.andEqualTo("chunk",sensor.getChunk());
            sensor.setStationid(record.getStationid());
            sensor.setDevicegroup(record.getDevicegroup());
            sensor.setLastcommunicationstatus(-1);
            sensor.setLastdatatime(new Date());
            sensor.setLastalarmlevel(0);
            sensor.setLastalarmmessage("");
            if(selectOneByExample(example)==null){
                if (insertSelective(sensor) == 0) {
                    ret = 0;
                }
            }
        }
        return ret;
    }

    public MyResult<Dtspartition> getList(Dtspartition record) {
        List<Dtspartition> list = new ArrayList<>();
        list = dtspartitionMapper.selectbytotal(record);
        MyResult<Dtspartition> result = new MyResult<Dtspartition>();
        if (list.size()!=0){
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list.size());
            result.setData(list);
        }else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }
    public int Update(Dtspartition record,Boolean byid) {
        if(byid)
            return dtspartitionMapper.updateByPrimaryKeySelective(record);
        else
            return dtspartitionMapper.updatebytotal(record);
    }

    public int Update(Dtssensor record, Boolean byid) {
        if (byid)
            return updateByPrimaryKeySelective(record);
        else{
            Example example =  new Example(Dtssensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("ipaddr",record.getIpaddr());
            criteria.andEqualTo("devicegroup",record.getDevicegroup());
            criteria.andEqualTo("stationid",record.getStationid());
            criteria.andEqualTo("chunk",record.getChunk());
            return updateByExampleSelective(record,example);
        }
    }

    public Dtspartition getModel(Dtspartition record) {
        return dtspartitionMapper.selectsinglebytotal(record);
    }
    public int add(Dtspartition record) {
        return dtspartitionMapper.insertSelective(record);
    }

    /**
     * 获取所有在运行的设备总条数
     * @param stationid
     * @param deviceaddr
     * @return
     */
    public int getTotalCount(int stationid, int deviceaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(deviceaddr);
        return selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
    }
    public int getAlarmCount(int stationid, int deviceaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(deviceaddr);
        record.setLastalarmlevel(2);
        return selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
    }

    /**
     * 获取预警中的设备总条数
     * @param stationid
     * @param deviceaddr
     * @return
     */
    public int getWarnCount(int stationid, int deviceaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(deviceaddr);
        record.setLastalarmlevel(1);
        return selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
    }

    /**
     * 获取通讯正常的（不判断报警不报警）设备总条数
     * @param stationid
     * @param deviceaddr
     * @return
     */
    public int getNormalCount(int stationid, int deviceaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(deviceaddr);
        record.setLastcommunicationstatus(0);
        return selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
    }
    /**
     * 根据Appdevice的stationid和devicegroup参数删除
     * @param ad
     * @return
     */
    public int Delete(Appdevice ad) {
        super.Delete(ad);
        Dtspartition record = new Dtspartition();
        record.setStationid(ad.getStationid());
        record.setDevicegroup(ad.getDevicegroup());
        return dtspartitionMapper.delete(record);
    }
    public int pDelete(Long id) {
        Dtspartition dtspartition = new Dtspartition();
        dtspartition.setId(id);
        if(dtspartitionMapper.deleteByPrimaryKey(dtspartition) != 0)
            return 1;
        else
            return 0;
    }
    /**
     * 获取通讯异常的（不判断报警不报警）设备总条数
     * @param stationid
     * @param deviceaddr
     * @return
     */
    public int getAbnormalCount(int stationid, int deviceaddr) {
        DefaultProperty record = new DefaultProperty();
        record.setStationid(stationid);
        record.setDevicegroup(deviceaddr);
        record.setLastcommunicationstatus(1);
        int abcount1 = selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
        record.setLastcommunicationstatus(-1);
        int abcount2 = selectCountByExample(ConditionDispose.defaultDispose(record,Dtssensor.class));
        return abcount1 + abcount2;
    }
    public List<alarmmessage> getAlarmmessageList(Appdevice ad) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<alarmmessage> list = new ArrayList<>();
        Example example = new Example(Dtspartition.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid",ad.getStationid());
        criteria.andEqualTo("devicegroup",ad.getDevicegroup());
        criteria.andNotEqualTo("lastalarmlevel",0);
        List<Dtspartition> sensorlist = dtspartitionMapper.selectByExample(example);
        for (int i = 0; i < sensorlist.size(); i++) {
            Integer lastcommunicationstatus = 0;
            Integer pointaddr = sensorlist.get(i).getChunk();
            Integer lastalarmlevel = sensorlist.get(i).getLastalarmlevel();
            String lastalarmmessage = sensorlist.get(i).getLastalarmmessage();
            alarmmessage am = new alarmmessage(sensorlist.get(i).getStationid(),
                    sensorlist.get(i).getDevicegroup(),
                    sensorlist.get(i).getDeviceaddr(),
                    pointaddr,
                    ad.getName(),
                    sensorlist.get(i).getPointname(),
                    lastcommunicationstatus,
                    sdf.format(new Date()),
                    lastalarmlevel,
                    lastalarmmessage);
            list.add(am);
        }
        return list;
    }
    /**
     * 查询历史表
     * @param record
     * @param pageBase
     * @return
     */
    public MyResult<Dtsphistory> getPHisList(Dtsphistory record, pagebase pageBase) {
        List<Dtsphistory> list = new ArrayList<>();
        Example example = new Example(Dtsphistory.class);
        Example.Criteria criteria = example.createCriteria();
        if (record.getStationid() != null) {
            criteria.andEqualTo("stationid", record.getStationid());
        }
        if (record.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", record.getDevicegroup());
        }
        if (record.getIpaddr() != null) {
            criteria.andEqualTo("ipaddr", record.getIpaddr());
        }
        if (record.getChunk() != null) {
            criteria.andEqualTo("chunk", record.getChunk());
        }
        if (record.getPartitionno() != null) {
            criteria.andEqualTo("partitionno", record.getPartitionno());
        }
        if (record.getPid() != null) {
            criteria.andEqualTo("pid", record.getPid());
        }
        if (pageBase.getBegintime() != null && pageBase.getEndtime() != null) {
            criteria.andBetween("datatime", pageBase.getBegintime(), pageBase.getEndtime());
        }
        example.orderBy("datatime").desc();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        list = dtsphistorymapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<Dtsphistory> hpi = new PageInfo<>(list);
            //获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if(list_size>0&&list_size<list.size()){
                //删除多余的查询条数
                list = list.subList(0, list.size()-list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        }else{
            PageInfo<Dtsphistory> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        MyResult<Dtsphistory> result = new MyResult<Dtsphistory>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(countNums);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }
       /**
     * 查询历史表
     * @param record
     * @param pageBase
     * @return
     */
    public MyResult<Dtshistory> getHisList(Dtshistory record, pagebase pageBase) {
        List<Dtshistory> list = new ArrayList<>();
        Example example = new Example(Dtshistory.class);
        Example.Criteria criteria = example.createCriteria();
        if (record.getStationid() != null) {
            criteria.andEqualTo("stationid", record.getStationid());
        }
        if (record.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", record.getDevicegroup());
        }
        if (record.getIpaddr() != null) {
            criteria.andEqualTo("ipaddr", record.getIpaddr());
        }
        if (record.getChunk() != null) {
            criteria.andEqualTo("chunk", record.getChunk());
        }
        if (pageBase.getBegintime() != null && pageBase.getEndtime() != null) {
            criteria.andBetween("datatime", pageBase.getBegintime(), pageBase.getEndtime());
        }
        example.orderBy("datatime").desc();
        PageHelper.startPage(pageBase.getPage(), pageBase.getLimit());
        list = dtshistorymapper.selectByExample(example);
        int countNums;
        if (pageBase.getPagecount() != null) {
            PageInfo<Dtshistory> hpi = new PageInfo<>(list);
            //获取当前页数据是否超过总查询条数
            int list_size = pageBase.getPage() * pageBase.getLimit() - pageBase.getPagecount();
            if(list_size>0&&list_size<list.size()){
                //删除多余的查询条数
                list = list.subList(0, list.size()-list_size);
            }
            countNums = (int) hpi.getTotal() > pageBase.getPagecount() ? pageBase.getPagecount() : (int) hpi.getTotal();
        }else{
            PageInfo<Dtshistory> hpi = new PageInfo<>(list);
            countNums = (int) hpi.getTotal();
        }
        MyResult<Dtshistory> result = new MyResult<Dtshistory>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(countNums);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }
    public Long AddAndGetId(Dtshistory record) {
        if(hisMapper.insertSelective(record) == 1){
            return record.getId();
        }
        else{
            return null;
        }
    }
    public void UpdateStatus(Dtssensor record){
        Example example = new Example(Dtssensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid",record.getStationid());
        criteria.andEqualTo("devicegroup",record.getDevicegroup());
        criteria.andEqualTo("ipaddr",record.getIpaddr());
        criteria.andEqualTo("chunk",record.getChunk());
        updateByExampleSelective(record, example);
    }
}
